package root.electronclass.electronclass.other

import android.app.AlertDialog
import android.content.DialogInterface
import android.graphics.Bitmap
import android.util.Log
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RadioGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import com.blankj.utilcode.util.ToastUtils
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.common.event.NetWorkEvent
import root.electronclass.electronclass.databinding.ActivityEntryFaceBinding
import root.electronclass.electronclass.personal.dialog.TipsDialog
import root.electronclass.electronclass.setup
import com.hikvision.smarteyes.common.SmartConsts
import com.hikvision.smarteyes.facelib.FaceBuildBean
import com.hikvision.smarteyes.smartdev.FaceSdk
import com.hikvision.smarteyes.smartdev.data.BuildModelEvent
import com.hikvision.smarteyes.smartdev.data.SmartDataEvent
import com.hikvision.smarteyes.utils.PicUtils
import com.hikvision.smarteyes.utils.log.DFLog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 * 人脸录入
 */
class EntryFaceActivity : ViewBindingActivity<ActivityEntryFaceBinding>(), View.OnClickListener {
    private val TAG = "EntryFaceActivity"
    private var mHolder: SurfaceHolder? = null
    private var mBitmap: MutableList<Bitmap>? = null
    private var faceNumIndex = 0

    override fun init() {
        binding.top.setup(lifecycle, "")
//        FaceSdk.get().startFaceRecog()

        binding.back.back.setOnClickListener {
            finish()
        }
        binding.snapBtnCapture.setOnClickListener(this)
        binding.btnCompareModel.setOnClickListener(this)
        binding.btnSavePic.setOnClickListener(this)
        mHolder = binding.faceInputSurfaceview.holder
        mHolder?.addCallback(SurfaceHolderCB(binding))
    }

    override fun onStart() {
        super.onStart()
        //使用前清空一下旧缓存数据
        FaceSdk.get().faceCaptureDatas
        FaceSdk.get().faceBuildResult
        /**
         * 使用eventbus 方式接收消息
         */
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: SmartDataEvent) {
        Log.i(TAG, "onEvent: DevSmartDataEvent")
        when (messageEvent.dataType) {
            SmartConsts.DEV_SMARTDATA_CAPTURE -> {
                //抓图
                val data = FaceSdk.get().faceCaptureDatas
                if (data == null) {
                    Log.i(TAG, "onEvent: data is null")
                    return
                }
                Log.i(
                    TAG,
                    "onEvent: DEV_SMARTDATA_CAPTURE len = " + data.size
                )
                if (mBitmap == null) {
                    mBitmap = mutableListOf()
                }

                for (i in data.indices) {
                    mBitmap!!.add(data[i].bmpPic)
                }
                faceNumIndex = 0
                binding.imgSnapFaceDisplay.setImageBitmap(mBitmap.orEmpty()[faceNumIndex])
            }

            SmartConsts.DEV_SMARTDATA_LOCATION -> showFaceDetectResult()
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkEvent(event: NetWorkEvent) {
//        binding.top.netWork(event.connect)
        if (!event.connect) {
            TipsDialog().also {
                it.arguments = bundleOf(
                    CommonDialogFragment.TITLE to "温馨提示",
                    CommonDialogFragment.CLOSE to true
                )
            }.show(supportFragmentManager, "TIPS")
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceive(buildModelEvent: BuildModelEvent) {
        Log.i(TAG, "DevStatusEvent = $buildModelEvent")
        //demo人脸录入同时只建模一个人脸数据。
        if (buildModelEvent.isDone) {
            val list = FaceSdk.get().faceBuildResult
            if (list == null || list.isEmpty()) {
                Toast.makeText(this, "人脸建模失败,未知错误，请查看日志。", Toast.LENGTH_SHORT).show()
            } else {
                val faceBuildBean = list[0]
                DFLog.i(
                    "",
                    list.size.toString() + " " + faceBuildBean.toString()
                )
                if (faceBuildBean.errCode != 0) {
                    Toast.makeText(
                        this,
                        "人脸建模失败,错误码：" + faceBuildBean.errCode,
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    Toast.makeText(this, "人脸建模成功。", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    /**
     * 显示人脸检测结果
     */
    private fun showFaceDetectResult() {
        val faceLocationDatas = FaceSdk.get().faceLocationDatas ?: return
        for (i in faceLocationDatas.indices) {
            val faceRectFs = faceLocationDatas[i].faceRectFS
            binding.faceInputFacerectview.setFaceRectFs(faceRectFs)
            Log.i(TAG, faceLocationDatas[i].toString())
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.snap_btn_capture -> {
                //开始抓拍
                if (mBitmap != null) {
                    mBitmap!!.clear()
                }
                binding.imgSnapFaceDisplay.setImageBitmap(null)
                //                FaceConfig fc = FaceSdk.get().getFaceConfig();
//                fc.setnFaceSelectType(0);
//                FaceSdk.get().setFaceConfig(fc);
                val ret = FaceSdk.get().startFaceCapture(SmartConsts.DEV_CAPTURE_ONCE)
                Log.i(TAG, "onClick: startCapture ret = $ret")
            }

            R.id.btn_compare_model -> {
                Log.i(TAG, "onClick: faceBuildModel")
                val builder = AlertDialog.Builder(this)
                val loginDialog =
                    LayoutInflater.from(this)
                        .inflate(R.layout.dialog_personinfo_input, null) as LinearLayout
                val inputName = loginDialog.findViewById<EditText>(R.id.et_personinfo_input_name)
                val radioGroup = loginDialog.findViewById<RadioGroup>(R.id.radioGroup)
                builder.setTitle("请输入信息").setView(loginDialog).setNegativeButton("取消", null)
                builder.setPositiveButton("确认", DialogInterface.OnClickListener { dialog, which ->
                    val name = inputName.text.toString()
                    if (mBitmap == null || mBitmap!!.isEmpty()) {
                        Toast.makeText(applicationContext, "请先抓拍人脸信息", Toast.LENGTH_SHORT)
                            .show()
                        return@OnClickListener
                    }
                    val bitmap = mBitmap!![faceNumIndex]
                    if (bitmap.isRecycled) {
                        Toast.makeText(applicationContext, "请先抓拍人脸信息", Toast.LENGTH_SHORT)
                            .show()
                        return@OnClickListener
                    }
                    if (name == "") {
                        Toast.makeText(applicationContext, "人脸id不能为空", Toast.LENGTH_SHORT)
                            .show()
                        return@OnClickListener
                    }
                    if (name.length > 64) {
                        Toast.makeText(applicationContext, "人脸id输入过长", Toast.LENGTH_SHORT)
                            .show()
                        return@OnClickListener
                    }
                    val folder = "/sdcard/faceCap/"
                    val file = File(folder)
                    if (!file.exists() || !file.isDirectory()) {
                        file.mkdirs()
                    }
                    PicUtils.saveBitmap2Jpg(mBitmap!![faceNumIndex], folder + name)
                    val fb = FaceBuildBean()
                    fb.faceUuid =
                        "${name}_${if (radioGroup.checkedRadioButtonId == R.id.student) 1 else 2}"
                    fb.picPath = folder + name
                    val list: MutableList<FaceBuildBean> = ArrayList()
                    list.add(fb)
                    FaceSdk.get().faceBuildResult
                    val ret = FaceSdk.get().faceBuild(list)
                    Log.i(
                        "",
                        "onClick: faceBuild ret = $ret"
                    )
                })
                builder.show()
            }

            R.id.btn_save_pic -> {
                Log.i(TAG, "onClick: faceBuildModel")
                val builder1 = AlertDialog.Builder(this)
                val loginDialog1 =
                    LayoutInflater.from(this)
                        .inflate(R.layout.dialog_personinfo_input, null) as LinearLayout
                val inputName1 = loginDialog1.findViewById<EditText>(R.id.et_personinfo_input_name)
                builder1.setTitle("请输入信息").setView(loginDialog1)
                    .setNegativeButton("取消", null)
                builder1.setPositiveButton(
                    "确认",
                    DialogInterface.OnClickListener { dialog, which ->
                        val name = inputName1.text.toString()
                        if (mBitmap == null || mBitmap!!.isEmpty()) {
                            Toast.makeText(
                                applicationContext,
                                "请先抓拍人脸信息",
                                Toast.LENGTH_SHORT
                            ).show()
                            return@OnClickListener
                        }
                        val bitmap = mBitmap!![faceNumIndex]
                        if (bitmap == null || bitmap.isRecycled) {
                            Toast.makeText(
                                applicationContext,
                                "请先抓拍人脸信息",
                                Toast.LENGTH_SHORT
                            ).show()
                            return@OnClickListener
                        }
                        if (name == "") {
                            Toast.makeText(applicationContext, "人脸id不能为空", Toast.LENGTH_SHORT)
                                .show()
                            return@OnClickListener
                        }
                        val folder = "/sdcard/faceCap/"
                        val file = File(folder)
                        if (!file.exists() || !file.isDirectory) {
                            file.mkdirs()
                        }
                        PicUtils.saveBitmap2Jpg(mBitmap!![faceNumIndex], "$folder$name.jpg")
                        ToastUtils.showShort("保存成功")

                    })
                builder1.show()
            }
        }
    }


    class SurfaceHolderCB(binding: ActivityEntryFaceBinding) : SurfaceHolder.Callback {
        val bind = binding
        override fun surfaceCreated(holder: SurfaceHolder) {
            val ret = FaceSdk.get().startPreview(bind.faceInputSurfaceview)
            if (ret != 0) {
                ToastUtils.showShort("播放错误，err = $ret")
            }
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
            //Log.e(MainActivity.TAG,"surfaceChanged");
        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            FaceSdk.get().stopPreview()
        }
    }


    override fun onStop() {
        super.onStop()
        FaceSdk.get().stopFaceTask()
        EventBus.getDefault().unregister(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "onDestroy: release")
    }


}